'''
Created on May 21, 2011

@author: Andrzej
'''
import os
import re 
import numpy as np
import matplotlib.pyplot as plt
from PyDaq.Sandbox.aserial import *
import time

if __name__ == '__main__':
    A = async_serial(13)    
    
    test1_cal = 0
    test2_run = 1
    
    print "Starting Test"
    if test1_cal:
        adc = np.array([[0.,0.,0.,0.,0.,0.]])
        error_vect = []
        error_norm = []
        error_cm = []
            
        weights = np.array([-3., -2., -1., 1., 2., 3.])
        max_vect = np.array([0., 0., 0., 0., 0., 0.])
        min_vect = np.array([255., 255., 255., 255., 255., 255.])
        print "Max adc: ", max_vect
        print "Starting for loop"
        
        to = time.time()
        for i in range(1,200):
            adc = np.append(adc, [A.query("adc", "</a>", "a", json=1)[1]], axis=0)
            if i == 100:
                print "reverse direction"        
            temp = adc[-1]
            ix_max = temp > max_vect
            ix_min = temp < min_vect        
            max_vect[ix_max] = temp[ix_max]
            min_vect[ix_min] = temp[ix_min]
            
            norm_adc = adc - min_vect
            norm_adc = 255 * norm_adc / max_vect
            
            error_cm.append( sum(adc[-1]*[1,2,3,4,5,6]*8)/sum(adc[-1])/8 - 3.5)
            
            error_vect.append(np.dot(np.array(adc[-1]),weights))
            error_norm.append(np.dot(norm_adc[-1],weights))
        tn = time.time()
        
        print "Elapsed time: ", tn - to, ' which is: ', 100.0/(tn - to), " vals per sec"
        
        
        
        data = np.array(adc)
        print data.shape
        print "Max adc: ", max_vect
        plt.subplot(411)
        plt.plot(data)
        plt.grid('on')
        
        plt.subplot(412)
        plt.contourf(np.transpose(adc))
        
        plt.subplot(413)
        plt.plot(error_vect)
        plt.grid('on')
        
        plt.subplot(414)
        plt.plot(error_cm)
        plt.show()
        
    #    os.chdir('E:\home\data')
    #    print os.getcwd()
    #    file_list = os.listdir(os.getcwd())
    #    print file_list
    #    cal = np.load('Cal_3.npy')
    #    plt.plot(cal[:,0:6])
    #    plt.show()
    #    pass
    if test2_run:
        
        A.start_thread()        
        A.send('l')
        time.sleep(4)
        A.send('q')
        out  = A.process_q()
        data = A.process_q()
        
        plt.plot(data)
        plt.xlabel("Sample index")
        plt.ylabel("Error")
        plt.grid(True)
        plt.show()
         
        
        
    print "Finished all test cases"
